const express = require('express');
const router = express.Router();
const { LoginsModel } = require('../models/Huser');
const Product = require('../models/Product');

const errorRes = (res, message, code = 400) => res.status(code).json({ code, message });

// 登录
router.post('/login', async (req, res) => {
  const { phone, password } = req.body;
  const user = await LoginsModel.findOne({ phone, password });
  if (user) {
    res.send({ code: 200, data: user });
  } else {
    res.send({ code: 500 });
  }
});

// 数据列表
router.get('/list', async (req, res) => {
  const list = await Product.find();
  res.send({ code: 200, list });
});

// 获取用户总数和年龄分布
router.get('/total-users', async (req, res) => {
  try {
    const users = await LoginsModel.find({});
    const ageRanges = [
      { ageRange: '18-24岁', min: 18, max: 24, count: 0 },
      { ageRange: '25-34岁', min: 25, max: 34, count: 0 },
      { ageRange: '35-44岁', min: 35, max: 44, count: 0 },
      { ageRange: '45-54岁', min: 45, max: 54, count: 0 },
      { ageRange: '55岁以上', min: 55, max: 100, count: 0 }
    ];
    let totalUsers = users.length;
    users.forEach(user => {
      if (user.age) {
        for (const range of ageRanges) {
          if (user.age >= range.min && user.age <= range.max) {
            range.count++;
            break;
          }
        }
      }
    });
    const ageDistribution = ageRanges.map(range => ({
      ageRange: range.ageRange,
      count: range.count,
      percentage: totalUsers > 0 ? Math.round((range.count / totalUsers) * 100) : 0
    }));
    res.status(200).json({
      code: 200,
      data: totalUsers,
      message: '获取用户年龄分布成功',
      ageDistribution
    });
  } catch (e) {
    res.status(500).json({
      code: 500,
      data: 0,
      message: '获取用户年龄分布失败',
      error: e.message
    });
  }
});

module.exports = router; 